package com.xrit.sunnyday.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Order;
import com.xrit.sunnyday.service.OrderService;
import com.xrit.sunnyday.utils.RedisMessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderMobileController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, String> paraMap) {
//        验证码的校验
        Jedis jedis = jedisPool.getResource();
//        获取手机号码
        String telephone = paraMap.get("telephone");
//        获取验证码的key并和手机号码拼接起来
        String key = RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
//        拿到redis中的验证码
        String codeInRedis = jedis.get(key);
//        判断redis中是否有值，如果为空就从新获取验证码
        if (StringUtils.isEmpty(codeInRedis)) {
//            没有值，就从新获取验证码
            return new Result(false, "请从新获取验证码!!!");
        }
//        从前端传入的验证码
        String validateCode = paraMap.get("validateCode");
//        判断验证码是否正确
        if (!codeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
//        移除redis中的验证码，防止重复提交
//        jedis.del(key);
//        预约成功页面展示时需要用到id
        Order order = orderService.submitOrder(paraMap);
//        添加成功给出提示
        return new Result(true, MessageConstant.ORDER_SUCCESS, order);
    }

    /**
     * 预约成功展示
     */
    @GetMapping("/findById")
    public Result findById(Integer id) {
        Map<String, Object> orderInfo = orderService.findById(id);
        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, orderInfo);
    }
}
